<template>
    <!-- 弹幕组件 -->
    <vue-danmaku v-model:danmus="danmus" :speeds="50" :channels="2" useSlot
        style="height:300px; width:600px; background-color: black;">
        <template v-slot:dm="{ danmu }">
            <!-- <img :src="danmu.img" :alt="danmu.nickName" class="img"> -->
            <!-- 显示弹幕的用户名和内容 -->
            {{ danmu.nickName }} -> {{ danmu.content }}
        </template>
    </vue-danmaku>
    <!-- 输入框和发送按钮 -->
    <el-input v-model="textarea" style="width: 240px" :rows="2" type="textarea" placeholder="请输入弹幕" />
    <el-button @click="send">发送</el-button>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { wmsStore } from '@/store/pinia';
import vueDanmaku from 'vue3-danmaku'
import { useRoute } from 'vue-router';
const route = useRoute();
const store = wmsStore();
const textarea = ref('');
const danmus = ref<any>([]);
const videoId = ref(0);
// videoId.value=Number(route.query.id)
    const protocol={
        token:store.token,
        videoId:videoId.value
    }

    let json=JSON.stringify(protocol)
// 建立WebSocket连接
var socket = new WebSocket('ws://localhost:8080/danmu',encodeURIComponent(json));
// 发送弹幕的函数
const send = () => {
    socket.send(textarea.value)
}
// 在组件挂载时执行
onMounted(() => {
    // 当WebSocket连接打开时
    socket.onopen = function (event) {
        console.log('连接已打开!');
    };
    // 当接收到服务器发送的消息时
    socket.onmessage = function (event) {
        let danmuData=JSON.parse(event.data)
        // 将接收到的弹幕数据添加到弹幕数组中
        danmus.value.push(danmuData)
    };
    // 当WebSocket连接关闭时
    socket.onclose = function (event) {
        console.log('断开!');
    };
})
</script>